package com.cn.shuangzi.userinfo.photo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;

import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.permission.RequestPermissionViewP;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.userinfo.R;
import com.cn.shuangzi.userinfo.bean.OSSTokenInfo;
import com.cn.shuangzi.userinfo.bean.PictureInfo;
import com.cn.shuangzi.userinfo.bean.UploadInfo;
import com.cn.shuangzi.userinfo.common.OSSManager;
import com.cn.shuangzi.userinfo.permission.RequestWritePermissionHelper;
import com.cn.shuangzi.userinfo.photo.adapter.GridImageAdapter;
import com.cn.shuangzi.userinfo.photo.compress.CompressImage;
import com.cn.shuangzi.userinfo.photo.compress.LuBanCompress;
import com.cn.shuangzi.userinfo.photo.listener.OnItemLongClickListener;
import com.cn.shuangzi.userinfo.photo.widget.FullyGridLayoutManager;
import com.cn.shuangzi.userinfo.photo.widget.GlideEngine;
import com.cn.shuangzi.util.SZFileUtil;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.broadcast.BroadcastAction;
import com.luck.picture.lib.broadcast.BroadcastManager;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnItemClickListener;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.style.PictureSelectorUIStyle;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.ScreenUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;

import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.LubanOptions;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;

public abstract class BasePictureActivity extends SZBaseActivity {
    private GridImageAdapter mAdapter;
    private ItemTouchHelper mItemTouchHelper;

    private int maxSelectNum;
    private List<LocalMedia> localMediaList;
    private List<UploadInfo> uploadInfoList;
    private OSSTokenInfo ossTokenInfo;
    /**
     * 返回结果回调
     */
    private class PictureResultCallback implements OnResultCallbackListener<LocalMedia> {
        private WeakReference<GridImageAdapter> mAdapterWeakReference;

        public PictureResultCallback(GridImageAdapter adapter) {
            super();
            this.mAdapterWeakReference = new WeakReference<>(adapter);
        }

        @Override
        public void onResult(List<LocalMedia> result) {
            localMediaList = result;
            if (SZApp.getInstance().isDebug()) {
                for (LocalMedia media : result) {
                    logLocalMedia(media);
                }
            }
            if (mAdapterWeakReference.get() != null) {
                mAdapterWeakReference.get().setList(result);
                mAdapterWeakReference.get().notifyDataSetChanged();
            }
            compress(result, false);
        }

        @Override
        public void onCancel() {
            SZUtil.logError("PictureSelector Cancel");
        }
    }

    private void compress(List<LocalMedia> imageList, final boolean isUpload) {
        if (isNeedCompress(imageList)) {
            final long compressBeginTime = System.currentTimeMillis();
            LubanOptions option = new LubanOptions.Builder().setMaxSize(400).create();
            CompressConfig config = CompressConfig.ofLuban(option);
//            config.enablePixelCompress(false);
            new LuBanCompress(getContext(), config, imageList, new CompressImage.CompressListener() {
                @Override
                public void onCompressSuccess(List<LocalMedia> images) {
                    SZUtil.logError("压缩成功，用时:" + (System.currentTimeMillis() - compressBeginTime));
                    if (SZApp.getInstance().isDebug()) {
                        for (LocalMedia localMedia : images) {
                            logLocalMedia(localMedia);
                        }
                    }
                    localMediaList = images;
                    if (isUpload) {
                        getSign();
                    }
                }

                @Override
                public void onCompressFailed(List<LocalMedia> images, String msg) {
                    SZUtil.logError("压缩失败：" + msg);
                    if (isUpload) {
                        closeBar();
                        SZToast.error("保存失败，请重试！");
                    }
                }
            }).compress();
        } else {
            if (isUpload) {
                getSign();
            }
        }
    }

    public void uploadFile() {
        if (isHasPicture()) {
            if(isHasUploadPicture()){
                compress(localMediaList, true);
            }else{
                onSubmit();
            }
        } else {
            onSubmit();
        }
    }

    private void getSign() {
        request(getSignObservable(), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                ossTokenInfo = new Gson().fromJson(data, OSSTokenInfo.class);
                uploadOSSFile();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                closeBar();
            }
        });
    }

    private void uploadOSSFile() {
        if(uploadInfoList == null){
            uploadInfoList = new ArrayList<>();
        }else{
            uploadInfoList.clear();
        }
        for (LocalMedia localMedia : localMediaList) {
            addUploadInfo(localMedia, ossTokenInfo.getFilePath());
        }

        if (SZValidatorUtil.isValidList(uploadInfoList)) {
            SZUtil.logError("====有需要上传的图片，开始上传====");
            new OSSManager(ossTokenInfo.getAccessKeyId(), ossTokenInfo.getAccessKeySecret(), ossTokenInfo.getSecurityToken(),
                    getEndpoint(), ossTokenInfo.getBucket()).uploadFileList(uploadInfoList, new OSSManager.OSSMultiUploadProgressListener() {
                @Override
                public void onUpload(UploadInfo uploadInfo, long currentSize, long totalSize) {
                    SZUtil.logError("currentSize:" + currentSize + "|||||totalSize:" + totalSize);
                }

                @Override
                public void onSuccess(List<UploadInfo> uploadInfoList) {
                    SZUtil.logError("上传成功:" + uploadInfoList);
                    for (UploadInfo uploadInfo : uploadInfoList) {
                        for (LocalMedia localMedia : localMediaList) {
                            if (uploadInfo.getUploadFilePath().equals(localMedia.getCompressPath())) {
                                localMedia.setPath(ossTokenInfo.getBaseURL() + uploadInfo.getObjName());
                                break;
                            }
                        }
                    }
                    onSubmit();
                }

                @Override
                public void onFailure(UploadInfo uploadInfo) {
                    SZUtil.logError("上传是失败："+uploadInfo);
                    SZToast.error(getString(R.string.error_net_work));
                    closeBar();
                }
            });
        } else {
            SZUtil.logError("====没有需要上传的图片，直接提交====");
            onSubmit();
        }
//        new OSSManager(ossTokenInfo.getAccessKeyId(), ossTokenInfo.getAccessKeySecret(), ossTokenInfo.getSecurityToken(),
//                getEndpoint(), ossTokenInfo.getBucket()).uploadFileList(uploadInfoList, new OSSManager.OSSMultiUploadProgressListener() {
//            @Override
//            public void onUpload(UploadInfo uploadInfo, long currentSize, long totalSize) {
//                SZUtil.logError("currentSize:" + currentSize + "|||||totalSize:" + totalSize);
//            }
//
//            @Override
//            public void onSuccess(List<UploadInfo> uploadInfoList) {
//                onSubmit();
//            }
//
//            @Override
//            public void onFailure(UploadInfo uploadInfo) {
//                closeBar();
//            }
//        });
    }

    private boolean isHasPicture() {
        return SZValidatorUtil.isValidList(localMediaList);
    }
    private boolean isHasUploadPicture(){
        boolean isHas = false;
        if(SZValidatorUtil.isValidList(localMediaList)) {
            for (LocalMedia localMedia : localMediaList){
                if(!SZUtil.isUrlPath(localMedia.getPath())){
                    isHas = true;
                    break;
                }
            }
        }
        return isHas;
    }

    public String getUploadImages() {
        List<PictureInfo> images = new ArrayList<>();
        if (isHasPicture()) {
            for (LocalMedia localMedia : localMediaList) {
                String url = null;
                if (SZUtil.isUrlPath(localMedia.getPath())) {
                    url = localMedia.getPath();
                } else {
                    String objName = getUploadObjName(localMedia.getRealPath());
                    if (SZValidatorUtil.isValidString(objName)) {
                        url =  ossTokenInfo.getBaseURL() + objName;
                    }
                }
                if (url != null) {
                    images.add(new PictureInfo(url, localMedia.getWidth(), localMedia.getHeight()));
                }
            }
        }
        return new Gson().toJson(images);
    }

    private String getUploadObjName(String realFilePath) {
        for (UploadInfo uploadInfo : uploadInfoList) {
            if (realFilePath.equals(uploadInfo.getRealFilePath())) {
                return uploadInfo.getObjName();
            }
        }
        return null;
    }

    private void addUploadInfo(LocalMedia localMedia, String objPath) {
        if(SZUtil.isUrlPath(localMedia.getPath())){
            return;
        }
        for (UploadInfo uploadInfo : uploadInfoList) {
            try {
                SZUtil.logError("localMedia.getRealPath()："+localMedia.getRealPath());
                SZUtil.logError("uploadInfo.getRealFilePath()："+uploadInfo.getRealFilePath());
                if (localMedia.getRealPath().equals(uploadInfo.getRealFilePath())) {
                    SZUtil.logError("路径相同，已上传，无需添加~");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        uploadInfoList.add(new UploadInfo(localMedia.getCompressPath(), objPath, localMedia.getRealPath()));
    }

    private boolean isNeedCompress(List<LocalMedia> imageList) {
        if (SZValidatorUtil.isValidList(imageList)) {
            for (LocalMedia localMedia : imageList) {
                if (!SZUtil.isUrlPath(localMedia.getPath()) && !localMedia.isCompressed()) {
                    return true;
                }
            }
        }
        return false;
    }

    public void init(RecyclerView mRecyclerView) {
        init(mRecyclerView, 9, null);
    }

    public void init(RecyclerView mRecyclerView, int maxSelectNum) {
        init(mRecyclerView, maxSelectNum, null);
    }

    public void init(RecyclerView mRecyclerView, List<PictureInfo> pictureInfoList) {
        init(mRecyclerView, 9, pictureInfoList);
    }

    public void init(RecyclerView mRecyclerView, final int maxSelectNum, List<PictureInfo> pictureInfoList) {
        uploadInfoList = new ArrayList<>();
        localMediaList = new ArrayList<>();
        this.maxSelectNum = maxSelectNum;
        if(mRecyclerView.getLayoutManager() == null) {
            FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                    4, GridLayoutManager.VERTICAL, false);
            mRecyclerView.setLayoutManager(manager);

            mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4,
                    ScreenUtils.dip2px(this, 8), false));

            // 注册广播
            BroadcastManager.getInstance(getContext()).registerReceiver(broadcastReceiver,
                    BroadcastAction.ACTION_DELETE_PREVIEW_POSITION);
        }
        mAdapter = new GridImageAdapter(getContext(), onAddPicClickListener,getAddPicResId());

        mAdapter.setSelectMax(maxSelectNum);
        if (SZValidatorUtil.isValidList(pictureInfoList)) {
            for (PictureInfo pictureInfo : pictureInfoList) {
                LocalMedia media = new LocalMedia();
                media.setPath(pictureInfo.getCompressUrl());
                media.setHeight(pictureInfo.getHeight());
                media.setWidth(pictureInfo.getWidth());
                localMediaList.add(media);
            }
        }
        mAdapter.setList(localMediaList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                List<LocalMedia> selectList = mAdapter.getData();
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String mimeType = media.getMimeType();
                    int mediaType = PictureMimeType.getMimeType(mimeType);
                    switch (mediaType) {
                        case PictureConfig.TYPE_VIDEO:
                            // 预览视频
                            PictureSelector.create(getActivity())
                                    .themeStyle(R.style.picture_default_style)
                                    .setPictureUIStyle(getNumUIStyle())
//                                .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
                                    .externalPictureVideo(TextUtils.isEmpty(media.getAndroidQToPath()) ? media.getPath() : media.getAndroidQToPath());
                            break;
                        case PictureConfig.TYPE_AUDIO:
                            // 预览音频
                            PictureSelector.create(getActivity())
                                    .externalPictureAudio(PictureMimeType.isContent(media.getPath()) ? media.getAndroidQToPath() : media.getPath());
                            break;
                        default:
                            // 预览图片 可自定长按保存路径
                            PictureSelector.create(getActivity())
                                    .themeStyle(R.style.picture_default_style) // xml设置主题
//                                .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
//                                .setPictureUIStyle(getNumUIStyle())
                                    .setPictureWindowAnimationStyle(PictureWindowAnimationStyle.ofCustomWindowAnimationStyle(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out))// 自定义页面启动动画
                                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                    .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                    .openExternalPreview(position, selectList);
                            break;
                    }
                }
            }
        });
        mAdapter.setItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(RecyclerView.ViewHolder holder, int position, View v) {
                //如果item不是最后一个，则执行拖拽
                int size = mAdapter.getData().size();
                if (size != maxSelectNum) {
                    mItemTouchHelper.startDrag(holder);
                    return;
                }
                if (holder.getLayoutPosition() != size - 1) {
                    mItemTouchHelper.startDrag(holder);
                }
            }
        });

        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            }

            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                int itemViewType = viewHolder.getItemViewType();
                if (itemViewType != GridImageAdapter.TYPE_CAMERA) {
                    viewHolder.itemView.setAlpha(0.7f);
                }
                return makeMovementFlags(ItemTouchHelper.DOWN | ItemTouchHelper.UP
                        | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, 0);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                //得到item原来的position
                try {
                    int fromPosition = viewHolder.getAdapterPosition();
                    //得到目标position
                    int toPosition = target.getAdapterPosition();
                    int itemViewType = target.getItemViewType();
                    if (itemViewType != GridImageAdapter.TYPE_CAMERA) {
                        if (fromPosition < toPosition) {
                            for (int i = fromPosition; i < toPosition; i++) {
                                Collections.swap(mAdapter.getData(), i, i + 1);
                            }
                        } else {
                            for (int i = fromPosition; i > toPosition; i--) {
                                Collections.swap(mAdapter.getData(), i, i - 1);
                            }
                        }
                        mAdapter.notifyItemMoved(fromPosition, toPosition);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
                int itemViewType = viewHolder != null ? viewHolder.getItemViewType() : GridImageAdapter.TYPE_CAMERA;
                if (itemViewType != GridImageAdapter.TYPE_CAMERA) {
                    super.onSelectedChanged(viewHolder, actionState);
                }
            }


            @Override
            public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                int itemViewType = viewHolder.getItemViewType();
                if (itemViewType != GridImageAdapter.TYPE_CAMERA) {
                    viewHolder.itemView.setAlpha(1.0f);
                    super.clearView(recyclerView, viewHolder);
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        // 绑定拖拽事件
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);

    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            if (isShowBuyVipAlert()) {
                showBuyVipAlertImg(getVipActivity());
                return;
            }
            requestPermission(getString(R.string.txt_request_write_permission_record),new RequestWritePermissionHelper(getActivity(),  new RequestPermissionViewP() {
                @Override
                public void onPermissionRequestSuccess(String[] permissionName) {
                    selectPicture();
                }

                @Override
                public void onRequestPermissionAlertCancelled(String[] permissionName) {
                    SZToast.error("您未授权文件存储权限！");
                }
            }));

        }
    };
    private void selectPicture(){
        boolean mode = true;//选择进相册模式
        if (mode) {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(getActivity())
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
//                        .theme(R.style.picture_default_style) // xml设置主题
                    //.theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                    .setPictureUIStyle(getNumUIStyle())
//                        .setPictureStyle(getNumStyle())// 动态自定义相册主题
                    //.setPictureCropStyle(mCropParameterStyle)// 动态自定义裁剪主题
                    .setPictureWindowAnimationStyle(PictureWindowAnimationStyle.ofCustomWindowAnimationStyle(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out))// 自定义相册启动退出动画
                    .isWeChatStyle(false)// 是否开启微信图片选择风格
                    .isUseCustomCamera(false)// 是否使用自定义相机
                    .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)// 列表动画效果
                    .isWithVideoImage(false)// 图片和视频是否可以同选,只在ofAll模式下有效
                    .isMaxSelectEnabledMask(true)// 选择数到了最大阀值列表是否启用蒙层效果
                    //.isAutomaticTitleRecyclerTop(false)// 连续点击标题栏RecyclerView是否自动回到顶部,默认true
                    //.loadCacheResourcesCallback(GlideCacheEngine.createCacheEngine())// 获取图片资源缓存，主要是解决华为10部分机型在拷贝文件过多时会出现卡的问题，这里可以判断只在会出现一直转圈问题机型上使用
                    //.setOutputCameraPath(createCustomCameraOutPath())// 自定义相机输出目录
                    //.setButtonFeatures(CustomCameraView.BUTTON_STATE_BOTH)// 设置自定义相机按钮状态
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .maxVideoSelectNum(1) // 视频最大选择数量
                    //.minVideoSelectNum(1)// 视频最小选择数量
                    //.closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 关闭在AndroidQ下获取图片或视频宽高相反自动转换
                    .imageSpanCount(4)// 每行显示个数
                    .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                    .closeAndroidQChangeWH(true)//如果图片有旋转角度则对换宽高,默认为true
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果视频有旋转角度则对换宽高,默认为false
                    .isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && .isEnableCrop(false);有效,默认处理
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义视频播放回调控制，用户可以使用自己的视频播放界面
                    //.bindCustomPreviewCallback(new MyCustomPreviewInterfaceListener())// 自定义图片预览回调接口
                    //.bindCustomCameraInterfaceListener(new MyCustomCameraInterfaceListener())// 提供给用户的一些额外的自定义操作回调
                    //.cameraFileName(System.currentTimeMillis() +".jpg")    // 重命名拍照文件名、如果是相册拍照则内部会自动拼上当前时间戳防止重复，注意这个只在使用相机时可以使用，如果使用相机又开启了压缩或裁剪 需要配合压缩和裁剪文件名api
                    //.renameCompressFile(System.currentTimeMillis() +".jpg")// 重命名压缩文件名、 如果是多张压缩则内部会自动拼上当前时间戳防止重复
                    //.renameCropFileName(System.currentTimeMillis() + ".jpg")// 重命名裁剪文件名、 如果是多张裁剪则内部会自动拼上当前时间戳防止重复
                    .selectionMode(
                            PictureConfig.MULTIPLE)// 多选 or 单选
                    .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                    .isPreviewImage(true)// 是否可预览图片
                    .isPreviewVideo(true)// 是否可预览视频
                    //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查询指定后缀格式资源
                    .isEnablePreviewAudio(true) // 是否可播放音频
                    .isCamera(false)// 是否显示拍照按钮
                    //.isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过，默认支持
                    //.isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                    .isEnableCrop(false)// 是否裁剪
                    //.basicUCropConfig()//对外提供所有UCropOptions参数配制，但如果PictureSelector原本支持设置的还是会使用原有的设置
                    .isCompress(false)// 是否压缩
//                        .compressQuality(80)// 图片压缩后输出质量 0~ 100
                    .synOrAsy(false)//同步true或异步false 压缩 默认同步
                    //.queryMaxFileSize(10)// 只查多少M以内的图片、视频、音频  单位M
                    //.compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效 注：已废弃
                    //.glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度 注：已废弃
                    .isGif(false)// 是否显示gif图片
                    //.isWebp(false)// 是否显示webp图片,默认显示
                    //.isBmp(false)//是否显示bmp图片,默认显示
//                        .freeStyleCropEnabled(cb_styleCrop.isChecked())// 裁剪框是否可拖拽
//                        .circleDimmedLayer(cb_crop_circular.isChecked())// 是否圆形裁剪
                    //.setCropDimmedColor(ContextCompat.getColor(getContext(), R.color.app_color_white))// 设置裁剪背景色值
                    //.setCircleDimmedBorderColor(ContextCompat.getColor(getApplicationContext(), R.color.app_color_white))// 设置圆形裁剪边框色值
                    //.setCircleStrokeWidth(3)// 设置圆形裁剪边框粗细
//                        .showCropFrame(cb_showCropFrame.isChecked())// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
//                        .showCropGrid(cb_showCropGrid.isChecked())// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .isOpenClickSound(false)// 是否开启点击声音
                    .selectionData(mAdapter.getData())// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
                    //.videoMinSecond(10)// 查询多少秒以内的视频
                    //.videoMaxSecond(15)// 查询多少秒以内的视频
                    //.recordVideoSecond(10)//录制视频秒数 默认60s
                    //.isPreviewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 注：已废弃 改用cutOutQuality()
//                        .cutOutQuality(90)// 裁剪输出质量 默认100
                    .minimumCompressSize(100)// 小于多少kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.cropImageWideHigh()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(false) // 裁剪是否可旋转图片
                    //.scaleEnabled(false)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                    .forResult(new PictureResultCallback(mAdapter));
        }
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            if (BroadcastAction.ACTION_DELETE_PREVIEW_POSITION.equals(action)) {
                // 外部预览删除按钮回调
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    int position = extras.getInt(PictureConfig.EXTRA_PREVIEW_DELETE_POSITION);
//                    ToastUtils.s(getContext(), "delete image index:" + position);
                    mAdapter.remove(position);
                    mAdapter.notifyItemRemoved(position);
                }
            }
        }
    };

    private void logLocalMedia(LocalMedia localMedia) {
        SZUtil.logError("=====================");
        SZUtil.logError("是否已压缩：" + localMedia.isCompressed());
        SZUtil.logError("压缩路径：" + localMedia.getCompressPath());
        SZUtil.logError("实际路径：" + localMedia.getRealPath());
        if (localMedia.getCompressPath() != null) {
            SZUtil.logError("压缩文件大小:" + SZFileUtil.getInstance().formatFileSize(new File(localMedia.getCompressPath()).length()));
        }
        SZUtil.logError("文件大小:" + SZFileUtil.getInstance().formatFileSize(localMedia.getSize()));

//                Util.log("是否裁剪:" + media.isCut());
//                Util.log("裁剪:" + media.getCutPath());
//                Util.log("是否开启原图:" + media.isOriginal());
//                Util.log("原图路径:" + media.getOriginalPath());
//                Util.log("Android Q 特有Path:" + media.getAndroidQToPath());
        SZUtil.logError("宽高: " + localMedia.getWidth() + "x" + localMedia.getHeight());
        // TODO 可以通过PictureSelectorExternalUtils.getExifInterface();方法获取一些额外的资源信息，如旋转角度、经纬度等信息
    }

    /**
     * 创建自定义拍照输出目录
     *
     * @return
     */
    private String createCustomCameraOutPath() {
        File customFile;
        if (SdkVersionUtils.checkedAndroid_Q()) {
            // 在Android Q上不能直接使用外部存储目录
            customFile = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        } else {
            File rootFile = Environment.getExternalStorageDirectory();
            customFile = new File(rootFile.getAbsolutePath() + File.separator + "CustomPictureCamera");
            if (!customFile.exists()) {
                customFile.mkdirs();
            }
        }
        return customFile != null ? customFile.getAbsolutePath() + File.separator : null;
    }

    public void savedInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getParcelableArrayList("selectorList") != null) {
            mAdapter.setList(savedInstanceState.<LocalMedia>getParcelableArrayList("selectorList"));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mAdapter != null && mAdapter.getData() != null && mAdapter.getData().size() > 0) {
            outState.putParcelableArrayList("selectorList",
                    (ArrayList<? extends Parcelable>) mAdapter.getData());
        }
    }

    private void clearCache() {
        try {
            SZFileUtil.getInstance().clearTmpFiles();
        } catch (Exception e) {
        }
        try {
            if (SZValidatorUtil.isValidList(localMediaList) && localMediaList.get(0).getCompressPath().contains("luban_disk_cache")) {
                SZFileUtil.getInstance().clearFile(new File(localMediaList.get(0).getCompressPath()).getParentFile());
            }
        } catch (Exception e) {
        }
        try {
            PictureFileUtils.deleteAllCacheDirFile(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SZUtil.logError("已上传图片文件:" + getUploadImages());
        SZUtil.logError("本地图片文件:" + localMediaList);
        try {
            if (broadcastReceiver != null) {
                BroadcastManager.getInstance(getContext()).unregisterReceiver(broadcastReceiver,
                        BroadcastAction.ACTION_DELETE_PREVIEW_POSITION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        clearCache();
    }

    public Context getContext() {
        return this;
    }

    public String getEndpoint() {
        return SZUtil.getAppMetaDataString(SZManager.getInstance().getContext(), SZConst.ENDPOINT);
    }

    public abstract PictureSelectorUIStyle getNumUIStyle();

    public abstract boolean isShowBuyVipAlert();

    public abstract Observable getSignObservable();

    public abstract Class getVipActivity();

    public abstract void onSubmit();

    public int getAddPicResId(){
        return 0;
    }
}
